// directives/loading.js
import Vue from 'vue'

// 创建 loading 组件构造器
const LoadingConstructor = Vue.extend({
  data() {
    return {
      visible: false,
      text: '',
      background: null
    }
  },
  methods: {
    handleAfterLeave() {
      this.$destroy()
      if (this.$el && this.$el.parentNode) {
        this.$el.parentNode.removeChild(this.$el)
      }
    }
  },
  render(h) {
    return h(
      'div',
      {
        style: {
          display: this.visible ? 'block' : 'none',
          position: 'absolute',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          zIndex: 9999,
          background: this.background || 'rgba(255, 255, 255, 0.7)'
        },
        class: 'v-loading-container'
      },
      [
        h(
          'a-spin',
          {
            props: {
              spinning: true,
              tip: this.text,
              // size: 'small'
            },
            style: {
              position: 'absolute',
              top: '50%',
              left: '50%',
              transform: 'translate(-50%, -50%)'
            }
          }
        )
      ]
    )
  }
})

// 插入 loading 元素
function insertLoading(el, binding) {
  const background = el.getAttribute('loading-background')
  const text = el.getAttribute('loading-text') || ''
  
  // 如果已经存在 loading 实例，则直接返回
  if (el.loadingInstance) {
    return el.loadingInstance
  }

  const loadingInstance = new LoadingConstructor({
    el: document.createElement('div'),
    data: {
      background,
      text
    }
  })

  el.loadingInstance = loadingInstance
  el.appendChild(loadingInstance.$el)
  
  return loadingInstance
}

// 切换 loading 状态
function toggleLoading(el, binding) {
  if (binding.value) {
    const loadingInstance = insertLoading(el, binding)
    Vue.nextTick(() => {
      loadingInstance.visible = true
    })
  } else {
    if (el.loadingInstance) {
      el.loadingInstance.visible = false
      // 添加过渡动画后移除
      setTimeout(() => {
        if (el.loadingInstance && el.loadingInstance.$el && el.loadingInstance.$el.parentNode) {
          el.loadingInstance.$el.parentNode.removeChild(el.loadingInstance.$el)
          el.loadingInstance.$destroy()
          el.loadingInstance = null
        }
      }, 300)
    }
  }
}

export default {
  inserted(el, binding) {
    // 确保元素有相对定位
    if (getComputedStyle(el).position === 'static') {
      el.style.position = 'relative'
    }
    
    toggleLoading(el, binding)
  },
  update(el, binding) {
    if (binding.oldValue !== binding.value) {
      toggleLoading(el, binding)
    }
  },
  unbind(el) {
    if (el.loadingInstance) {
      el.loadingInstance.$destroy()
      el.loadingInstance = null
    }
  }
}